package org.linlinjava.litemall.db.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ListIntegerTypeHandler extends BaseTypeHandler<List<Integer>> {

    // 将 List<Integer> 转换为逗号分隔的字符串存储
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<Integer> parameter, JdbcType jdbcType) throws SQLException {
        // 将 List 转换为逗号分隔的字符串
        StringBuilder str = new StringBuilder();
        for (int j = 0; j < parameter.size(); j++) {
            str.append(parameter.get(j));
            if (j < parameter.size() - 1) {
                str.append(",");
            }
        }
        ps.setString(i, str.toString());
    }

    // 从 ResultSet 中获取字符串并转换为 List<Integer>
    @Override
    public List<Integer> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String result = rs.getString(columnName);
        if (result == null || result.isEmpty()) {
            return new ArrayList<>();
        }
        return stringToList(result);
    }

    // 从 ResultSet 中获取字符串并转换为 List<Integer> (通过列索引)
    @Override
    public List<Integer> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String result = rs.getString(columnIndex);
        if (result == null || result.isEmpty()) {
            return new ArrayList<>();
        }
        return stringToList(result);
    }

    // 从 CallableStatement 获取字符串并转换为 List<Integer>
    @Override
    public List<Integer> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String result = cs.getString(columnIndex);
        if (result == null || result.isEmpty()) {
            return new ArrayList<>();
        }
        return stringToList(result);
    }

    // 辅助方法：将逗号分隔的字符串转换为 List<Integer>
    private List<Integer> stringToList(String result) {
        String[] items = result.split(",");
        List<Integer> list = new ArrayList<>();
        for (String item : items) {
            list.add(Integer.parseInt(item.trim()));
        }
        return list;
    }
}
